<?php

namespace Hilaoyu\LaravelExtend\Services\ThirdPartyLogin\Controllers;




use Hilaoyu\LaravelExtend\ControllerBase;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelExtend\Services\ThirdPartyLogin\ThirdPartyLoginService;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class ThirdPartyLoginController extends ControllerBase
{


    protected function guardKey()
    {
        return \request()->route('guard','');
    }

    /**
     * 生成第三方登录的跳转链接
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws AuthenticationException
     */
    public function buildLinks(Request $request)
    {

        $third_login_provider = AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'allow_third_path_login');

        $provider_config = [];
        if(!$third_login_provider || !($provider_config = config('third_party_login.providers.'.$third_login_provider,false))){
            abort(404);
        }
        $back_url = $request->input('back_url', '');
        $bind_user = $request->input('bind_user', '');
        $bind_user_id = '';
        /*if (1 == $bind_user && !($bind_user_id = $this->authenticatedUser('id'))) {
            throw new AuthenticationException();
        }*/

        $entity = new ThirdPartyLoginService();
        $links = [];
        collect($provider_config)->filter(function ($item,$key){
            return Str::startsWith($key,'driver_');
        })
        ->each(function ($item,$key) use ($third_login_provider,$entity,$back_url,$bind_user,&$links){
            $driver = Str::after($key,'driver_');
            $entity::clientAllowedDrivers($driver)->map(function ($driver_config,$driver_key) use ($third_login_provider,$entity,$back_url,$bind_user,&$links){
                //$link = $entity->buildLoginUrl($provider,$driver_key, $guard, $bind_user_id,$back_url);
                $link = route('web.l-e-s.third_party_login.go',[
                    'guard' =>AuthService::GuardKey(),
                    'driver_key'=>$driver_key,
                    'bind_user'=>$bind_user,
                    'back_url'=>$back_url,
                ]);
                if(!$link){
                    comResponse()->withErrors($entity->getError());
                }
                data_set($driver_config,'url',$link);
                $links[] =  $driver_config;
            });
        });



        comResponse()->success()->with($links);

        return $this->renderingResponse();
    }

    public function thirdLoginGo(Request $request){
        $guard = $request->route('guard', '');
        $driver_key = $request->route('driver_key', '');
        $back_url = $request->input('back_url', '');
        $bind_user = $request->input('bind_user', '');

        $provider = AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'allow_third_path_login');

        $entity = new ThirdPartyLoginService();
        if(!$provider || !($entity::getProviderConfig($provider))){
            abort(404);
        }


        if (empty($driver_key) || !($driver = $entity::CreateDriver($driver_key))) {
            abort(404);
        }


        if(! $entity::getProviderConfig($provider,'driver_' . $driver->getDriverName())){
            abort(404);
        }


        $bind_user_id = '';
        if (1 == $bind_user && !($bind_user_id = $this->authenticatedUser('id'))) {
            throw new AuthenticationException();
        }

        $link = $entity->buildLoginUrl($driver_key,$guard, [
            'guard' => $guard,
            'driver_key' => $driver_key,
            'back_url' => $back_url,
            'bind_user_id' => $bind_user_id,
        ]);

        if(!$link){
            return comResponse()->withErrors($entity->getError())->back();
        }

        return redirect($link);

    }

    /**
     * 处理
     */
    public function thirdLoginReturn(Request $request)
    {

        $code = $request->input('code', '');
        $state = $request->input('state', '');

        $entity = new ThirdPartyLoginService();
        $user = $entity->login($code, $state);

        dd($entity::StateCacheGet($state));

        $guard_key = $entity::StateCacheGet($state,'guard');



        if($user && $guard_key){
            try{
                $guard = Auth::guard($guard_key);
                $guard->logout();

                $guard->setUser($user);
                $guard->login($user);
            }catch (\Exception $exception){

            }

        }



        return comResponse()->redirect(route('client.redirect_back'));
        //return comResponse()->redirect(route('users.logedin'));

    }

}
